package com.xxx.sso.config;

import com.xxx.sso.enums.ErrEnum;
import com.xxx.sso.util.Result;
import com.xxx.sso.util.ResultBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.stream.Collectors;

/**
 * @author caiwl
 * @date 2020/5/8 11:22
 */
@ControllerAdvice
@Slf4j
public class MyExceptionHandler {
    @ExceptionHandler({BindException.class})
    @ResponseBody
    public Result handle(BindException e) {
        String msg = e.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(","));
        log.error("BindException: {}", msg);
        return ResultBuilder.fail(ErrEnum.ERR_CLIENT_PARAM);
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Result handle(Exception e) {
        log.error("Exception: {}", e.getMessage());
        return ResultBuilder.fail();
    }
}
